<?php

namespace app\ask\controller;

use think\Controller;
use app\common\library\Email;

class Business extends Controller
{
    public function __construct()
    {
        // 这里继承了home的构造函数，相当于继承了home里面的所有它自己写的所有方法，其实是有在调用。
        // 这里其实继承了home的构造函数，相当于继承了home里面的所有它自己写的
        parent::__construct();

        //公共区域加载模型
        $this->BusinessModel = model('Business.Business');
        $this->PostModel = model('Post.Post');
        $this->CommentModel = model('Post.Comment');
        $this->CollectModel = model('Post.Collect');
        $this->AttentionModel = model('Post.Attention');
        $this->FansModel = model('Post.Fans');
        $this->LetterModel = model('Post.Letter');
    }

    // 授权登录
    public function login()
    {
        // 判断是否有请求
        if ($this->request->isPost()) {
            // 接收参数
            $code = $this->request->param('code', '', 'trim');
            // var_dump($code);
            // exit;

            // 如果为空
            if (empty($code)) {
                $this->error('临时凭证获取失败');
                exit;
            }

            // 发送请求给微信端
            $wxauth = $this->code2Session($code);

            // 拿到openid
            $openid = isset($wxauth['openid']) ? $wxauth['openid'] : '';

            // openid为空
            if (empty($openid)) {
                $this->error('授权失败');
                exit;
            }

            // 不为空，根据这个openid查找这个用户
            $business = $this->BusinessModel->where(['openid' => $openid])->find();
            unset($business['password']);
            unset($business['salt']);

            if ($business) {
                //授权成功
                $this->success('授权登录成功', null, $business);
                exit;
            } else {
                $this->success('授权成功，请绑定账号', "/pages/business/login", ['action' => 'bind', 'openid' => $openid]);
                exit;
            }
        }
    }

    // 绑定账号
    public function bind()
    {
        // 判断是否是post请求
        if ($this->request->isPost()) {
            // 接收参数
            $openid = $this->request->param('openid', '', 'trim');
            $password = $this->request->param('password', '', 'trim');
            $mobile = $this->request->param('mobile', '', 'trim');

            // 查询用户是否存在
            $business = $this->BusinessModel->where(['mobile' => $mobile])->find();

            // 存在------做更新语句（将openid更新进去）
            if ($business) {
                // 判断该用户的openid是否为空，不为空才插入，否则是已经有绑定l
                if (!empty($business['openid'])) {
                    $this->error('该用户已绑定，无法重复绑定');
                    exit;
                }

                // 组装数据，进行更新
                $data = [
                    'id' => $business['id'],
                    'openid' => $openid
                ];

                // 更新
                $result = $this->BusinessModel->isUpdate(true)->save($data);

                // 如果失败
                if ($result === FALSE) {
                    $this->error('绑定账号失败');
                    exit;
                } else {
                    unset($business['password']);
                    unset($business['salt']);
                    $business['openid'] = $openid;
                    $this->success('绑定账号成功', null, $business);
                    exit;
                }
                // 不存在------插入语句，将新用户插入数据库表
            } else {
                //数据插入
                if (empty($password)) {
                    $this->error('密码不能为空');
                    exit;
                }

                //生成一个密码盐
                $salt = randstr();

                //加密密码
                $password = md5($password . $salt);

                //组装数据
                $data = [
                    'openid' => $openid,
                    'mobile' => $mobile,
                    'nickname' => $mobile,
                    'password' => $password,
                    'salt' => $salt,
                    'gender' => '0', //性别
                    'deal' => '0', //成交状态
                    'money' => '0', //余额
                    'auth' => '0', //实名认证
                ];

                //查询出云课堂的渠道来源的ID信息 数据库查询
                $data['sourceid'] = model('common/Business/Source')->where(['name' => ['LIKE', "%知识社区%"]])->value('id');

                //执行插入 返回自增的条数
                $result = $this->BusinessModel->validate('common/Business/Business')->save($data);

                if ($result === FALSE) {
                    //失败
                    $this->error($this->BusinessModel->getError());
                    exit;
                } else {
                    //查询出当前插入的数据记录
                    $business = $this->BusinessModel->find($this->BusinessModel->id);

                    //注册
                    $this->success('注册成功', null, $business);
                    exit;
                }
            }
        }
    }

    // 解除账号
    public function unbind()
    {
        // 判断是否是post请求
        if ($this->request->isPost()) {
            // 接收参数
            $busid = $this->request->param('busid', '', 'trim');
            $openid = $this->request->param('openid', '', 'trim');

            // 判断用户是否存在
            if (!$busid) {
                $this->error('解绑用户不存在');
                exit;
            }

            // 如果存在，则判断是否有openid
            if (!$openid) {
                $this->error('该用户没有授权登录');
                exit;
            }

            // 组装数据，更新语句（解绑将openid置为null）
            $data = [
                'id' => $busid,
                'openid' => null,
            ];

            // 更新
            $result = $this->BusinessModel->isUpdate(true)->save($data);

            // 如果失败
            if ($result === FALSE) {
                $this->error('解绑账号失败');
                exit;
            } else {
                $this->success('解绑账号成功');
                exit;
            }
        }
    }

    // 注册登录
    public function webLogin()
    {
        if ($this->request->isPost()) {
            $password = $this->request->param('password', '', 'trim');
            $mobile = $this->request->param('mobile', '', 'trim');

            $business = $this->BusinessModel->where(['mobile' => $mobile])->find();

            //如果找得到就说明绑定过， 如果找不到就说明账号不存在，就注册插入
            if ($business) {
                //验证密码是否正确
                $salt = $business['salt'];
                $password = md5($password . $salt);

                if ($password != $business['password']) {
                    $this->error('密码错误');
                    exit;
                } else {
                    unset($business['salt']);
                    unset($business['password']);
                    $this->success('登录成功', null, $business);
                    exit;
                }
            } else {
                //数据插入
                if (empty($password)) {
                    $this->error('密码不能为空');
                    exit;
                }

                //生成一个密码盐
                $salt = randstr();

                //加密密码
                $password = md5($password . $salt);

                //组装数据
                $data = [
                    'mobile' => $mobile,
                    'nickname' => $mobile,
                    'password' => $password,
                    'salt' => $salt,
                    'gender' => '0', //性别
                    'deal' => '0', //成交状态
                    'money' => '0', //余额
                    'auth' => '0', //实名认证
                ];

                //查询出云课堂的渠道来源的ID信息 数据库查询
                $data['sourceid'] = model('common/Business/Source')->where(['name' => ['LIKE', "%问答社区%"]])->value('id');

                //执行插入 返回自增的条数
                $result = $this->BusinessModel->validate('common/Business/Business')->save($data);

                if ($result === FALSE) {
                    //失败
                    $this->error($this->BusinessModel->getError());
                    exit;
                } else {
                    //查询出当前插入的数据记录
                    $business = $this->BusinessModel->find($this->BusinessModel->id);

                    unset($business['salt']);
                    unset($business['password']);

                    //注册
                    $this->success('注册成功', null, $business);
                    exit;
                }
            }
        }
    }

    // 基本资料
    public function profile()
    {
        //判断是否有Post过来数据
        if ($this->request->isPost()) {
            //可以一次性接收到全部数据
            $id = $this->request->param('id', 0, 'trim');
            $nickname = $this->request->param('nickname', '', 'trim');
            $mobile = $this->request->param('mobile', '', 'trim');
            $email = $this->request->param('email', '', 'trim');
            $gender = $this->request->param('gender', '0', 'trim');
            $code = $this->request->param('code', '', 'trim');
            $password = $this->request->param('password', '', 'trim');

            //判断用户是否存在
            $business = $this->BusinessModel->find($id);

            if (!$business) {
                $this->error('用户不存在');
                exit;
            }

            // 直接组装数据
            $data = [
                'id' => $business['id'], //因为我们要执行更新语句
                'nickname' => $nickname,
                'mobile' => $mobile,
                'gender' => $gender,
            ];

            //如果密码不为空 修改密码
            if (!empty($password)) {
                //重新生成一份密码盐
                $salt = randstr();

                $data['salt'] = $salt;
                $data['password'] = md5($password . $salt);
            }

            //判断是否修改了邮箱 输入的邮箱 不等于 数据库存入的邮箱
            //如果邮箱改变，需要重新认证
            if ($email != $business['email']) {
                $data['email'] = $email;
                $data['auth'] = '0';
            }

            //判断是否有地区数据
            if (!empty($code)) {
                //查询省市区的地区码出来
                $parent = model('Region')->where(['code' => $code])->value('parentpath');

                if (!empty($parent)) {
                    $arr = explode(',', $parent);
                    $data['province'] = isset($arr[0]) ? $arr[0] : null;
                    $data['city'] = isset($arr[1]) ? $arr[1] : null;
                    $data['district'] = isset($arr[2]) ? $arr[2] : null;
                }
            }

            //判断是否有图片上传
            if (isset($_FILES['avatar']) && $_FILES['avatar']['error'] == 0) {
                $success = build_upload('avatar');

                //如果上传失败，就提醒
                if (!$success['result']) {
                    $this->error($success['msg']);
                    exit;
                }

                //如果上传成功
                $data['avatar'] = $success['data'];
            }

            //执行更新语句 数据验证 -> 需要用到验证器

            //这是插入语句
            // $result = $this->BusinessModel->validate('common/Business/Business')->save($data);

            //更新语句 如果是更新语句，需要给data提供一个主键id的值 这就是更新语句 使用验证器的场景
            $result = $this->BusinessModel->validate('common/Business/Business.profile')->isUpdate(true)->save($data);

            if ($result === FALSE) {
                $this->error($this->BusinessModel->getError());
                exit;
            }

            //判断是否有旧图片，如果有就删除
            if (isset($data['avatar'])) {
                is_file("." . $business['avatar']) && @unlink("." . $business['avatar']);
            }

            $business = $this->BusinessModel->find($id);

            unset($business['password']);
            unset($business['salt']);

            $this->success('更新资料成功', null, $business);
            exit;
        }
    }

    // 用户邮箱验证
    public function email()
    {

        //加载模型
        $EmsModel = model('common/Ems');

        // 判断是否有接收到ajax请求
        if ($this->request->isPost()) {
            // 拿到action
            $action = $this->request->param('action', '', 'trim');

            //接收用户id
            $id = $this->request->param('id', 0, 'trim');

            $business = $this->BusinessModel->find($id);

            if (!$business) {
                $this->error('用户不存在');
                exit;
            }

            // 获取用户信息
            $email = isset($business['email']) ? $business['email'] : '';

            // 判断邮箱是否为空
            if (empty($email)) {
                // 提醒
                $this->error("邮箱地址为空");
                exit;
            }

            // action拿到
            if ($action == 'send') {

                // 如果邮箱不为空
                // 生成一个随机5位验证码
                $code = randstr(5);

                // 开启事务（撤销回滚操作）
                $EmsModel->startTrans();

                // 删掉之前的旧的验证码
                $EmsModel->where(['email' => $email])->delete();

                // 把验证码插入到数据库的pre_ems表中
                // 组装数据
                $data = [
                    'event' => 'auth',
                    'email' => $email,
                    'code' => $code,
                    'times' => 0,
                ];

                // 插入数据
                $ems = $EmsModel->save($data);

                // 如果插入失败
                if ($ems === FALSE) {
                    // 提示
                    $this->error('邮件插入失败');
                    exit;
                }

                // 插入成功

                $name = config('site.name');
                // 设置主题
                $subject = "【{$name}】邮箱验证";

                //组装文字信息
                $message = "<div>感谢您的使用，您的邮箱验证码为：<b>$code</b></div>";

                //实例化邮箱验证类
                $PhpMailer = new Email;

                //邮箱发送有规律，不可以发送关键词
                $result = $PhpMailer
                    ->to($email)
                    ->subject($subject)
                    ->message($message)
                    ->send();

                // 检测邮箱是否发送成功
                if ($result) {
                    //发送验证码成功
                    //将事务提交，提交的意思就是让刚刚插入的记录真实存在到数据表中
                    $EmsModel->commit();
                    $this->success('邮件发送成功，请注意查收');
                    exit;
                } else {
                    //将刚才插入成功的验证码记录要撤销回滚
                    $EmsModel->rollback();
                    $this->error($PhpMailer->getError());
                }
            } else {
                // 获取输入的验证码
                $code = $this->request->param('code', '', 'trim');

                // 判断是否为空
                if (empty($code)) {
                    // 提示
                    $this->error('验证码不能为空');
                    exit;
                }

                // 开启事务
                $EmsModel->startTrans();
                $this->BusinessModel->startTrans();

                // 查询验证码是否在数据库中存在，就是是否等于数据库中的验证码
                $where = ['email' => $email, 'code' => $code];
                $check = $EmsModel->where($where)->find();

                // 如果没有找到记录
                if (!$check) {
                    // 提示
                    $this->error("您输入的验证码有误！请重新输入~~");
                    exit;
                }

                // 1.更新用户表，2.删除验证码记录

                // 组装数据
                $data = [
                    'id' => $business['id'],
                    'auth' => '1'
                ];

                // 1.执行更新用户表
                $BusinessStatus = $this->BusinessModel->isUpdate(true)->save($data);

                // 如果更新用户表失败
                if ($BusinessStatus === FALSE) {
                    $this->error('用户邮箱认证失败');
                    exit;
                }

                // 2.删除验证码记录
                $EmsStatus = $EmsModel->where($where)->delete();

                // 如果删除验证码记录失败，要进行回滚
                if ($EmsStatus === FALSE) {
                    //先要将用户表的更新进行回滚
                    $this->BusinessModel->rollback();
                    $this->error('验证码记录删除失败');
                    exit;
                }

                // 如果两个中的其中一个没有成功，则验证也是失败的
                if ($BusinessStatus === FALSE || $EmsStatus === FALSE) {
                    $EmsModel->rollback();
                    $this->BusinessModel->rollback();
                    $this->error('验证失败');
                    exit;
                } else {
                    //提交事务
                    $this->BusinessModel->commit();
                    $EmsModel->commit();
                    $business = $this->BusinessModel->find($id);

                    unset($business['password']);
                    unset($business['salt']);

                    $this->success('邮箱验证成功', null, $business);
                }
            }
        }
    }

    // 基本资料灭有上传头像
    public function notAvatar()
    {
        //判断是否有Post过来数据
        if ($this->request->isPost()) {
            //可以一次性接收到全部数据
            $id = $this->request->param('id', 0, 'trim');
            $nickname = $this->request->param('nickname', '', 'trim');
            $mobile = $this->request->param('mobile', '', 'trim');
            $email = $this->request->param('email', '', 'trim');
            $gender = $this->request->param('gender', '0', 'trim');
            $code = $this->request->param('code', '', 'trim');
            $password = $this->request->param('password', '', 'trim');

            //判断用户是否存在
            $business = $this->BusinessModel->find($id);

            if (!$business) {
                $this->error('用户不存在');
                exit;
            }

            // 直接组装数据
            $data = [
                'id' => $business['id'], //因为我们要执行更新语句
                'nickname' => $nickname,
                'mobile' => $mobile,
                'gender' => $gender,
            ];

            //如果密码不为空 修改密码
            if (!empty($password)) {
                //重新生成一份密码盐
                $salt = randstr();

                $data['salt'] = $salt;
                $data['password'] = md5($password . $salt);
            }

            //判断是否修改了邮箱 输入的邮箱 不等于 数据库存入的邮箱
            //如果邮箱改变，需要重新认证
            if ($email != $business['email']) {
                $data['email'] = $email;
                $data['auth'] = '0';
            }

            //判断是否有地区数据
            if (!empty($code)) {
                //查询省市区的地区码出来
                $parent = model('Region')->where(['code' => $code])->value('parentpath');

                if (!empty($parent)) {
                    $arr = explode(',', $parent);
                    $data['province'] = isset($arr[0]) ? $arr[0] : null;
                    $data['city'] = isset($arr[1]) ? $arr[1] : null;
                    $data['district'] = isset($arr[2]) ? $arr[2] : null;
                }
            }

            //执行更新语句 数据验证 -> 需要用到验证器

            //这是插入语句
            // $result = $this->BusinessModel->validate('common/Business/Business')->save($data);

            //更新语句 如果是更新语句，需要给data提供一个主键id的值 这就是更新语句 使用验证器的场景
            $result = $this->BusinessModel->validate('common/Business/Business.profile')->isUpdate(true)->save($data);

            if ($result === FALSE) {
                $this->error($this->BusinessModel->getError());
                exit;
            }

            $business = $this->BusinessModel->find($id);

            unset($business['password']);
            unset($business['salt']);

            $this->success('更新资料成功', null, $business);
            exit;
        }
    }

    // 个人主页（我的提问、我的回答、我的收藏）
    public function post()
    {
        // 判断是否有post请求
        if ($this->request->isPost()) {
            // 接收参数
            $page = $this->request->param('page', 1, 'trim');
            $busid = $this->request->param('busid', 0, 'trim');
            $checkid = $this->request->param('checkid', 0, 'trim');
            $keywords = $this->request->param('keywords', '', 'trim');
            $limit = 5;
            //判断用户是否存在
            $business = $this->BusinessModel->find($busid);

            if (!$business) {
                $this->error('用户不存在');
                exit;
            }



            // 设置偏移量
            $offset = ($page - 1) * $limit;

            if ($checkid == 0) {
                $where = ['post.busid' => $busid];
                if (!empty($keywords)) {
                    $where['title'] = ['like', "%$keywords%"];
                }
                // 查询帖子表中的数据
                $list = $this->PostModel
                    ->with(['cate', 'business'])
                    ->where($where)
                    ->order('id', 'desc')
                    ->limit($offset, $limit)
                    ->select();
            } else if ($checkid == 1) {
                $where = ['comment.busid' => $busid];
                if (!empty($keywords)) {
                    $where['post.title'] = ['like', "%$keywords%"];
                }
                // 查询评论表的数据
                $list = $this->CommentModel
                    ->with(['business', 'post'])
                    ->where($where)
                    ->order('id', 'desc')
                    ->limit($offset, $limit)
                    ->select();
            } else {
                $where = ['collect.busid' => $busid];
                if (!empty($keywords)) {
                    $where['post.title'] = ['like', "%$keywords%"];
                }
                // 查询收藏表的数据
                $list = $this->CollectModel
                    ->with(['business', 'post'])
                    ->where($where)
                    ->order('id', 'desc')
                    ->limit($offset, $limit)
                    ->select();
            }

            if ($list) {
                $this->success('返回帖子数据', null, $list);
                exit;
            } else {
                $this->error('暂无更多数据');
                exit;
            }
        }
    }

    // 个人主页（个人信息）
    public function person()
    {
        // 判断是否是post请求
        if ($this->request->isPost()) {
            // 接收参数
            $busid = $this->request->param('busid', 0, 'trim');

            //判断用户是否存在
            $business = $this->BusinessModel->find($busid);

            if (!$business) {
                $this->error('用户不存在');
                exit;
            }

            // 计算出用户的提问数量，回答数量，收藏数量
            $PostCount = $this->PostModel->where(['busid' => $busid])->count();
            $CommentCount = $this->CommentModel->where(['busid' => $busid])->count();
            $CollectCount = $this->CollectModel->where(['busid' => $busid])->count();

            // 组装数据
            $data = [
                'business' => $business,
                'postCount' => $PostCount,
                'commentCount' => $CommentCount,
                'collectCount' => $CollectCount
            ];

            $this->success('返回个人信息', null, $data);
        }
    }

    // 我的关注
    public function attention()
    {
        // 判断是否有post请求
        if ($this->request->isPost()) {
            // 接收参数
            $page = $this->request->param('page', 1, 'trim');
            $busid = $this->request->param('busid', 0, 'trim');
            $checkid = $this->request->param('checkid', 0, 'trim');
            $keywords = $this->request->param('keywords', '', 'trim');
            $limit = 5;
            //判断用户是否存在
            $business = $this->BusinessModel->find($busid);

            if (!$business) {
                $this->error('用户不存在');
                exit;
            }

            // 设置偏移量
            $offset = ($page - 1) * $limit;

            if ($checkid == 0) {
                $where = ['attentionid' => $busid];
                if (!empty($keywords)) {
                    $where['business.nickname'] = ['like', "%$keywords%"];
                }
                // 查询关注表中的数据
                $list = $this->AttentionModel
                    ->with(['business'])
                    ->where($where)
                    ->order('id', 'desc')
                    ->limit($offset, $limit)
                    ->select();
            } else {
                $where = ['fansid' => $busid];
                if (!empty($keywords)) {
                    $where['business.nickname'] = ['like', "%$keywords%"];
                }
                // 查询粉丝表的数据
                $list = $this->FansModel
                    ->with(['business'])
                    ->where($where)
                    ->order('id', 'desc')
                    ->limit($offset, $limit)
                    ->select();
            }

            if ($list) {
                $this->success('返回帖子数据', null, $list);
                exit;
            } else {
                $this->error('暂无更多数据');
                exit;
            }
        }
    }

    // 取消关注
    public function unattention()
    {
        // 判断是否有post请求
        if ($this->request->isPost()) {
            // 接收参数
            // 自己
            $busid = $this->request->param('busid', 0, 'trim');
            // 关注的人
            $attentionid = $this->request->param('attentionid', 0, 'trim');

            //判断用户是否存在
            $business = $this->BusinessModel->find($busid);

            if (!$business) {
                $this->error('用户不存在');
                exit;
            }

            // 查找关注表中是否有这条关注的数据
            $attention = $this->AttentionModel->where(['busid' => $attentionid, 'attentionid' => $busid])->find();
            if ($attentionStatus === FALSE) {
                $this->error('没有关注过此人');
                exit;
            }
            // 查询粉丝表中是否有这条数据
            $Fans = $this->FansModel->where(['busid' => $attentionid, 'fansid' => $busid])->find();
            if ($FansStatus === FALSE) {
                $this->error('不是该人的粉丝');
                exit;
            }

            if ($attention && $Fans) {
                // 开启事务
                $this->AttentionModel->startTrans();
                $this->FansModel->startTrans();

                // 执行删除语句
                $attentionStatus = $this->AttentionModel->where(['busid' => $attentionid, 'attentionid' => $busid])->delete();

                if ($attentionStatus === FALSE) {
                    $this->error('删除关注人失败');
                    exit;
                }

                // 执行删除语句
                $FansStatus = $this->AttentionModel->where(['busid' => $attentionid, 'fansid' => $busid])->delete();

                if ($attentionStatus === FALSE) {
                    $this->AttentionModel->rollback();
                    $this->error('删除粉丝失败');
                    exit;
                }

                if ($attentionStatus === FALSE || $FansStatus === FALSE) {
                    $this->AttentionModel->rollback();
                    $this->FansModel->rollback();
                    $this->error('取消关注失败');
                    exit;
                } else {
                    $this->FansModel->commit();
                    $this->AttentionModel->commit();
                    $this->success('取消关注成功');
                    exit;
                }
            }
        }
    }

    // 我的私信
    public function letter()
    {
        // 判断是否有post请求
        if ($this->request->isPost()) {
            // 接收参数
            $page = $this->request->param('page', 1, 'trim');
            $busid = $this->request->param('busid', 0, 'trim');
            $keywords = $this->request->param('keywords', '', 'trim');
            $limit = 5;

            //判断用户是否存在
            $business = $this->BusinessModel->find($busid);

            if (!$business) {
                $this->error('用户不存在');
                exit;
            }

            // 设置偏移量
            $offset = ($page - 1) * $limit;

            $where = ['busid' => $busid];
            if (!empty($keywords)) {
                $where['business.nickname'] = ['like', "%$keywords%"];
            }

            // 查询帖子表中的数据
            $list = $this->LetterModel
                ->with(['business'])
                ->where($where)
                ->order('id', 'desc')
                ->limit($offset, $limit)
                ->select();

            $data['list'] = $list;

            if ($data) {
                $this->success('返回帖子数据', null, $data);
                exit;
            } else {
                $this->error('暂无更多数据');
                exit;
            }
        }
    }

    // 发送私信
    public function message()
    {
        // 判断是否有post请求
        if ($this->request->isPost()) {
            // 接收参数
            $content = $this->request->param('content', '', 'trim');
            // 接收人的id
            $busid = $this->request->param('busid', '', 'trim');
            // 发送人的id
            $sendid = $this->request->param('sendid', '', 'trim');

            //判断用户是否存在
            $business = $this->BusinessModel->find($busid);

            if (!$business) {
                $this->error('用户不存在');
                exit;
            }

            // 插入私信表

            // 组装数据
            $data = [
                'content' => $content,
                'sendid' => $sendid,
                'busid' => $busid,
            ];

            // 插入
            $result = $this->LetterModel->save($data);

            // 判断
            if ($result) {
                $this->success('私信成功');
                exit;
            } else {
                $this->error('私信失败');
                exit;
            }
        }
    }

    // 已读私信
    public function read()
    {
        // 判断是否有post请求
        if ($this->request->isPost()) {
            // 接收人的id
            $busid = $this->request->param('busid', '', 'trim');
            // 发送人的id
            $sendid = $this->request->param('sendid', '', 'trim');
            // 当前点击的私信
            $letterid = $this->request->param('letterid', '', 'trim');

            //判断用户是否存在
            $business = $this->BusinessModel->find($busid);

            if (!$business) {
                $this->error('用户不存在');
                exit;
            }
            // 组装条件
            $where = [
                'busid' => $busid,
                'sendid' => $sendid,
                'id' => $letterid,
            ];

            // 查询私信表中是否有该私信
            $result = $this->LetterModel->where($where)->find();

            // 有
            if ($result) {
                // 组装数据
                $data = [
                    'id' => $letterid,
                    'status' => '1'
                ];

                // 更新私信表中的状态
                $LetterStatus = $this->LetterModel->isUpdate(true)->save($data);

                if ($LetterStatus) {
                    $this->success('查看成功');
                    exit;
                } else {
                    $this->error('查看失败');
                    exit;
                }
            }
        }
    }

    // 删除私信
    public function delete()
    {
        if ($this->request->isPost()) {
            // 接收人的id
            $busid = $this->request->param('busid', '', 'trim');
            // 当前点击的私信
            $letterid = $this->request->param('letterid', '', 'trim');

            $business = $this->BusinessModel->find($busid);

            if (!$business) {
                $this->error('用户不存在');
                exit;
            }

            // 删除语句
            $result = $this->LetterModel->where(['id' => $letterid])->delete();

            if ($result === FALSE) {
                $this->error('删除私信失败');
                exit;
            } else {
                $this->success('删除私信成功');
                exit;
            }
        }
    }

    // 每个人个人详情主页
    public function personal()
    {
        // 判断是否是post请求
        if ($this->request->isPost()) {
            // 接收参数
            // 关注人id
            $busid = $this->request->param('busid', 0, 'trim');
            // 自己的id
            $attentionid = $this->request->param('attentionid', 0, 'trim');

            //判断用户是否存在
            $business = $this->BusinessModel->find($busid);

            if (!$business) {
                $this->error('用户不存在');
                exit;
            }

            // 计算出用户的提问数量，回答数量，收藏数量
            $PostCount = $this->PostModel->where(['busid' => $busid])->count();
            $CommentCount = $this->CommentModel->where(['busid' => $busid])->count();
            $CollectCount = $this->CollectModel->where(['busid' => $busid])->count();

            // 组装条件
            $where = [];
            $where = [
                'attentionid' => $attentionid,
                'busid' => $busid
            ];

            // 查询关注表状态
            $attention = $this->AttentionModel->where($where)->find();

            if (!empty($attention)) {
                // 组装数据
                $data = [
                    'business' => $business,
                    'postCount' => $PostCount,
                    'commentCount' => $CommentCount,
                    'collectCount' => $CollectCount,
                    'attention' => true
                ];

                $this->success('返回个人信息', null, $data);
            } else {
                // 组装数据
                $data = [
                    'business' => $business,
                    'postCount' => $PostCount,
                    'commentCount' => $CommentCount,
                    'collectCount' => $CollectCount,
                    'attention' => false
                ];

                $this->success('返回个人信息', null, $data);
            }
        }
    }

    // 调用微信官方获取用户信息
    public function code2Session($code)
    {

        if ($code) {

            // 改成自己的小程序 appid
            $appid = "wxccb8a47b7af619ba";

            // 改成自己的小程序 appSecret
            $appSecret = "70a955d6722913fb613af907df0ac79a";

            // 微信官方提供的接口，获取唯一的opendid
            $url = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$appSecret&js_code=$code&grant_type=authorization_code";

            $result = $this->https_request($url);

            //获取结果 将json转化为数组
            $resultArr = json_decode($result, true);

            return $resultArr;
        }
        return false;
    }

    //http请求 利用php curl扩展去发送get 或者 post请求 服务器上面一定要开启 php curl扩展
    // https://www.php.net/manual/zh/book.curl.php
    protected function https_request($url, $data = null)
    {
        if (function_exists('curl_init')) {
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
            if (!empty($data)) {
                curl_setopt($curl, CURLOPT_POST, 1);
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            }
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
            // 发送会话，返回结果
            $output = curl_exec($curl);
            curl_close($curl);
            return $output;
        } else {
            return false;
        }
    }
}
